package com.itguigu.glimail.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.itguigu.common.to.OrderTo;
import com.itguigu.common.to.mq.SeckillOrderTo;
import com.itguigu.common.utils.R;
import com.itguigu.glimail.oauth.vo.MemberRespVo;
import com.itguigu.glimail.order.constant.OrderConstant;
import com.itguigu.glimail.order.entity.OrderItemEntity;
import com.itguigu.glimail.order.entity.PaymentInfoEntity;
import com.itguigu.glimail.order.enume.OrderStatusEnum;
import com.itguigu.glimail.order.exception.NoStockException;
import com.itguigu.glimail.order.feign.CartFeignService;
import com.itguigu.glimail.order.feign.MemberFeignService;
import com.itguigu.glimail.order.feign.ProductFeignService;
import com.itguigu.glimail.order.feign.WmsFeignService;
import com.itguigu.glimail.order.interceptor.LoginUserInterceptor;
import com.itguigu.glimail.order.service.OrderItemService;
import com.itguigu.glimail.order.service.PaymentInfoService;
import com.itguigu.glimail.order.to.OrderCreateTo;
import com.itguigu.glimail.order.vo.*;

import org.aspectj.weaver.ast.Or;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itguigu.common.utils.PageUtils;
import com.itguigu.common.utils.Query;

import com.itguigu.glimail.order.dao.OrderDao;
import com.itguigu.glimail.order.entity.OrderEntity;
import com.itguigu.glimail.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    WmsFeignService wmsFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    private ThreadLocal<OrderSubmitVo> orderSubmitVoThreadLocal = new ThreadLocal<>();
    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        //远程调用查询用户地址
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        Long id = memberRespVo.getId();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();//异步调用  导致feign丢失上下文

        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);//同步上下文
            List<MemberAddressVo> address = memberFeignService.getAddress(id);
            confirmVo.setAddress(address);
        }, executor);


        //远程查询购物车被勾选的购物项
        CompletableFuture<Void> cartItemsFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);//同步上下文
            List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(currentUserCartItems);
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            R skusHasStock = wmsFeignService.getSkusHasStock(collect);
            if (skusHasStock.getCode() == 0) {
                List<SkuStockVo> data = skusHasStock.getData(new TypeReference<List<SkuStockVo>>() {
                });
                if (data != null) {
                    Map<Long, Boolean> stockMap = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                    confirmVo.setStock(stockMap);
                }
            }
        }, executor);
        //feign  在远程调用之前要构造请求,调用很多的拦截器

        //远程查询用户积分
        Integer integration = memberRespVo.getIntegration();
        confirmVo.setIntegration(integration);
        //其他数据自动计算
        //todo 防重令牌
        String token = UUID.randomUUID().toString().replace(("-"), "");
        confirmVo.setOrderToken(token);
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), token, 30, TimeUnit.MINUTES);

        CompletableFuture.allOf(addressFuture, cartItemsFuture).get();

        return confirmVo;
    }
//事务的坑
    //在同一个类里面，编写两个方法，内部调用的时候，会导致事务设置失效。原因是没有用到代理对象的缘故

    /**
     * 解决:
     * 0)、导入spring-boot-starter-aop
     * 1)、@EnableTransactionManagement(proxyTargetClass= true)
     * 2)、@EnableAspectAutoProxy(exposeProxy=true)
     * 3)、AopContext.currentProxy() 调用方法
     * <p>
     * 1
     */


//    @Transactional(propagation = Propagation.REQUIRED)
//    public void a() {
//
//        OrderServiceImpl o = (OrderServiceImpl) AopContext.currentProxy();
//        o.b();//回滚
//        o.c();//不会滚  因为是新事物
//        int i = 10 / 0;
//        //
//    }
//     @Transactional(propagation = Propagation.REQUIRES_NEW)
//    public void c() {
//
//    }
//     @Transactional
//    public void b() {
//
//    }



    //分布式事务  最大原因  网络问题
//    @GlobalTransactional
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {
        orderSubmitVoThreadLocal.set(orderSubmitVo);
        //验证令牌
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        String orderToken = orderSubmitVo.getOrderToken();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        responseVo.setCode(0);
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        //0总是代表失败
        String redisKey = OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId();
        //原子验证令牌和删除令牌
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script,Long.class), Arrays.asList(redisKey), orderToken);
        if (result == 0L) {
            //验证失败
            responseVo.setCode(1);
            return responseVo;
        } else {
            //验证成功
            //创建订单
            OrderCreateTo order = createOrder();
            //验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
            double abs = Math.abs(payAmount.subtract(payPrice).doubleValue());
            if (abs < 0.01) {
                //金额对比
                //......
                //todo 保存订单
                saveOrder(order);
                //锁定库存  有异常回滚
                //订单号 所有订单项(skuId skuname num)
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(locks);
                //todo 远程锁库存
                //库存成功了,但是网络原因超时了,订单回滚,库存不会滚

//                为了保证高并发库存服务自己回滚,可以发消息给库存服务
                //库存服务本身也可以使用自动解锁模式 消息演示队列
                R r = wmsFeignService.orderLockStock(lockVo);
                if (r.getCode() == 0) {
                    //锁定成功
                    responseVo.setOrder(order.getOrder());
                    //todo 远程扣减积分
                    //TODO 订单创建成功,发送消息给我们的mq
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
//                    int i = 10 / 0;
                    return responseVo;
                } else {
                    //锁定失败
                  String msg = (String) r.get("msg");
                  throw new NoStockException(msg);

//                   responseVo.setCode(3);
//                  return responseVo;
                }

            } else {
                responseVo.setCode(2);
                return responseVo;
            }


        }

//        String redisToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());
//        if (orderToken != null && orderToken.equals(redisToken)) {
//            //令牌验证通过  必须保障原子性
//
//            return null;
//        } else {
//            //不通过
//            responseVo.setCode(1);
//        }
//            return responseVo;
//        }


    }

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {

        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order_sn;
    }

    @Override
    public void closeOrder(OrderEntity entity) {
        //查询当前订单的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        if (orderEntity.getStatus()==OrderStatusEnum.CREATE_NEW.getCode()) {
            //关单
            OrderEntity updateEntity = new OrderEntity();
            updateEntity.setId(entity.getId());
            updateEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(updateEntity);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);
            //发给mq
            try {
                //todo 保证消息一定会发送出去 每i消息
                //      TODO 保证消息定会发送出去，每一一个消息都可以做好8志记录(给数据库保存每一 个消息的详细信息)
                //TODO 定期扫描数据库将失败的消息再发送一遍;

                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
            } catch (AmqpException e) {
                //todo 将没发送出去的消息进行重试发送.
                e.printStackTrace();
            }
        }


    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        OrderEntity order = this.getOrderByOrderSn(orderSn);
        PayVo payVo = new PayVo();
        BigDecimal payAmount = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(payAmount.toString());
        payVo.setOut_trade_no(orderSn);
        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity itemEntity = order_sn.get(0);
        String skuName = itemEntity.getSkuName();
        payVo.setSubject(skuName);
        payVo.setBody(itemEntity.getSkuAttrsVals());

        return payVo;

    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId()).orderByDesc("id")
        );
        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));

            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(order_sn);
        return new PageUtils(page);

    }

    /**
     * 处理支付宝的处理结果
     *
     * @param payAsyncVo
     * @return
     */
    @Autowired
    PaymentInfoService paymentInfoService;
    @Override
    public String handlePayResult(PayAsyncVo payAsyncVo) {

        //保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(infoEntity.getAlipayTradeNo());
        infoEntity.setOrderSn(infoEntity.getOrderSn());
        infoEntity.setPaymentStatus(payAsyncVo.getTrade_status());
        infoEntity.setCallbackTime(payAsyncVo.getNotify_time());
        paymentInfoService.save(infoEntity);
        //2、修改订单的状态信息

        if (payAsyncVo.getTrade_status().equals("TRADE_SUCCESS") || payAsyncVo.getTrade_status().equals("TRADE_FINISHED")) {
            //支付成功状态
            String outTradeNo = payAsyncVo.getOut_trade_no();
            this.baseMapper.updateOrderPayedStatus(outTradeNo, OrderStatusEnum.PAYED.getCode());

        }
        return "success";

    }

    @Override
    public void createSeckillOrder(SeckillOrderTo seckillTo) {
        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillTo.getOrderSn());
        orderEntity.setMemberId(seckillTo.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = seckillTo.getSeckillPrice().multiply(new BigDecimal("" + seckillTo.getNum()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);
        //TODO 保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillTo.getOrderSn());
        orderItemEntity.setRealAmount(multiply);
        orderItemEntity.setSkuQuantity(seckillTo.getNum());

        //TODO 获取当前信息sku的详细信息 进行设置 productFeignService.getSpuInfobySkuId();
        orderItemService.save(orderItemEntity);
    }

    /**
     * 保存 订单数据
     *
     * @param order
     */

    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
//        for (OrderItemEntity orderItem : orderItems) {
//            orderItemService.getBaseMapper().insert(orderItem);
//        }
    }

    private OrderCreateTo createOrder() {
        OrderCreateTo orderTo = new OrderCreateTo();
        //生成订单号
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity = buildOrderEntity(orderSn);
        //获取所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);
        //验价//计算价格相关
        computePrice(orderEntity, itemEntities);
        orderTo.setOrder(orderEntity);
        orderTo.setOrderItems(itemEntities);

        return orderTo;
    }

    /**
     * 订单价格
     *
     * @param orderEntity
     * @param itemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        for (OrderItemEntity entity : itemEntities) {
            BigDecimal realAmount = entity.getRealAmount();
            BigDecimal couponAmount = entity.getCouponAmount();
            coupon = coupon.add(couponAmount);
            BigDecimal integrationAmount = entity.getIntegrationAmount();
            integration = integration.add(integrationAmount);
            BigDecimal promotionAmount = entity.getPromotionAmount();
            promotion = promotion.add(promotionAmount);
            total = total.add(realAmount);
            growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));
            gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));

        }
        //订单价格相关
        orderEntity.setTotalAmount(total);
        //应付金额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);
        //设置积分信息
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setDeleteStatus(0);


    }

    /**
     * 构建所有订单项数据
     *
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后确定每一个购物项的价格
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (currentUserCartItems != null && currentUserCartItems.size() > 0) {
            List<OrderItemEntity> itemEntities = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity orderItemEntity = buildOrderItem(cartItem);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    private OrderEntity buildOrderEntity(String orderSn) {

        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        orderEntity.setMemberId(memberRespVo.getId());
        OrderSubmitVo orderSubmitVo = orderSubmitVoThreadLocal.get();
        //获取收货地址信息
        R fare = wmsFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareResp = fare.getData(new TypeReference<FareVo>() {
        });
        //设置运费信息
        orderEntity.setFreightAmount(fareResp.getFare());
//        设置收货人信息
        orderEntity.setReceiverCity(fareResp.getAddress().getCity());
        orderEntity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        orderEntity.setReceiverName(fareResp.getAddress().getName());
        orderEntity.setReceiverPhone(fareResp.getAddress().getPhone());
        orderEntity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        orderEntity.setReceiverProvince(fareResp.getAddress().getProvince());
        orderEntity.setReceiverRegion(fareResp.getAddress().getRegion());
        //设置订单状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        return orderEntity;
    }

    /**
     * 构建订某一个单项
     *
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1.订单信息:订单号
        //1.商品spu信息
        R spuInfo = productFeignService.getSpuInfobySkuId(cartItem.getSkuId());
        SpuInfoVo spuInfoVo = spuInfo.getData(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(spuInfoVo.getId());
        itemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
        itemEntity.setSpuName(spuInfoVo.getSpuName());
        itemEntity.setCategoryId(spuInfoVo.getCatalogId());


        //1.商品sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        List<String> skuAttrs = cartItem.getSkuAttr();
        String skuAttr = StringUtils.collectionToDelimitedString(skuAttrs, ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //优惠...
        //积分
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        //订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));

        //档前订单项的实际金额 总额减去各种优惠

        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = orign.subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);
        return itemEntity;
    }

}
